# -*- encoding: utf-8 -*- 
""" API for accessing www.stv.sk streams/videos """

__all__ = ["STVPlugin"]

from lib.basePlugin import *
import urllib


class STVPlugin(BasePlugin):
    LOGPREFIX = "[STV plugin] "
    BASE_URL = "http://www.stv.sk"

    @plugin_folder
    def root(self):
        """ plugin root folder """
        self.core.setSorting('NONE')
        yield PFolder(label=u'Videoarchív', call='videoarchiv')


    @plugin_folder
    def videoarchiv(self):
        """ videoarchiv - list programs """
        self.wget.request(self.BASE_URL + '/videoarchiv/')
        for e in self.wget.select('#right_bar li a'):
            yield PFolder(label=e.text, call='relacia',
                            param={'path': e['href']} )


    @plugin_folder
    def relacia(self, path):
        """ relacia - list periods """
        url = self.BASE_URL + path
        self.wget.request(url)
        iframe = self.wget.select_first('#left_bar iframe')

        if not iframe:
            raise '"#left_bar iframe" not found in: ' + url

        iframe_url = iframe['src']
        self.debug('relacia iframe url: ' + iframe_url)
        self.wget.request(iframe_url)
        
        form_dalsi = self.wget.select_first('form#dalsi')
        prog = form_dalsi.select_first('input[name=prog]')['value']
        for opt in form_dalsi.select('select option'):
            yield PFolder(label=opt.text, call='vitems',
                            param={'prog': prog, 'period': opt['value']} )


    @plugin_folder
    def vitems(self, **data):
        """ list vides for program and period """
        self.wget.request('http://stv.livetv.sk/tvarchive//video/vitems.html', data)

        for li in self.wget.select('li'):
            video = li.select_first('input[name=video]')['value']
            info = {'plot': (unicode(li.contents[-1]) or '').strip() }
            text = li.select_first('a').text
            yield PItem(label=text, call='play',
                        param={'video': video}, info=info )


    @plugin_call
    def play(self, video):
        """ play video call """
        url = 'http://stv.livetv.sk/tvarchive//video/playlist/playlist.wvx?video='+video
        self.wget.request(url)
        stream_url = self.wget.select_first('ref')['href']
        self.debug('Playing stream url: '+url)
        self.core.play(stream_url)
        
